package com.cws.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import com.cws.bridge.CommonConstant;
import com.cws.web.GridRequestData;
import com.cws.web.GridResponseData;
import com.cws.web.UserSession;

public class BaseController {
	
	/** 基于@ExceptionHandler异常处理 */  
    @ExceptionHandler  
    public ModelAndView handleException(HttpServletRequest request, Exception ex) {  
          
        ModelAndView mv = new ModelAndView("jsp/error/error");
		mv.addObject("ex", ex.getLocalizedMessage());
        return mv;  
    }


	public UserSession getUserSession(HttpServletRequest request) {
		return (UserSession) request.getSession().getAttribute(CommonConstant.USER_CONTEXT);
	}

	public void setUserSession(HttpServletRequest request,UserSession userSession) {
		request.getSession().setAttribute(CommonConstant.USER_CONTEXT, userSession);
	}
	
	public GridRequestData getDataRequest(HttpServletRequest request) {
		return (GridRequestData) request.getSession().getAttribute(CommonConstant.GRID_REQUEST_DATA);
	}

	@ModelAttribute("") 
	public void setDataRequest(HttpServletRequest request,GridRequestData dataRequest) {
		request.getSession().setAttribute(CommonConstant.GRID_REQUEST_DATA, dataRequest);
	}

    
    public <T> GridResponseData<T> transformDataPage(HttpServletRequest request,List<T> list){
    	GridRequestData dataRequest = getDataRequest(request);
    	int page = dataRequest.getPage();//当前页
    	int pageSize = dataRequest.getRows();//当前页显示数量
    	int begin=(page-1)*pageSize;
		int end=page*pageSize;
    	int totalSize = list.size();//数据总数
    	if(end > totalSize){
    		end = totalSize;
		}
    	int totalPage = (totalSize+pageSize-1)/pageSize;
    	int currPage = Math.min(totalPage, page);  
    	
    	GridResponseData<T> gridResponseData = new GridResponseData<T>(list.subList(begin, end),currPage,totalSize,totalPage);
    	
    	return gridResponseData;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
